<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>修改密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form :model="userInfo" :rules="rules" label-width="100px" size="large">
          <el-form-item label="登录名称">
            <el-input v-model="userInfo.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="原密码" prop="old_pwd">
            <el-input v-model="old_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input v-model="new_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="re_pwd">
            <el-input v-model="re_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePassword">修改密码</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import { updatePwd } from "@/api/user.js";
import { ElMessage } from "element-plus";
import { useUserInfoStore } from "@/stores/userinfo.js";
import { useTokenStore } from "@/stores/token.js"
const usertoken = useTokenStore()
import {useRouter} from 'vue-router'
const router = useRouter()

const userInfoStore = useUserInfoStore();
const userInfo = ref({
  ...userInfoStore.info
})

const old_pwd = ref('');
const new_pwd = ref('');
const re_pwd = ref('');

const updatePassword = async () => {
  const token = usertoken.token;
  const params = {
    old_pwd: old_pwd.value,
    new_pwd: new_pwd.value,
    re_pwd: re_pwd.value
  };
  try {
    const result = await updatePwd(params, token);
    if (result.code === 0) {
      ElMessage.success('修改成功');
      old_pwd.value = '';
      new_pwd.value = '';
      re_pwd.value = '';

      userInfoStore.removeInfo();
      usertoken.removeToken();
      //跳转到登录页
      router.push('/')

    } else {
      ElMessage.error(result.msg);
    }
  } catch (error) {
    ElMessage.error('请求出错，请稍后重试');
  }
}
</script>

<style scoped>
/* 这里可以添加样式 */
</style>
